import React, { useRef, useEffect, useState } from 'react';
import { Typography, Card, Row, Col, Table, Tag, Statistic } from 'antd';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

interface RisingResponse {
  totalRisingCompanies: number;
  companies: Enterprise[];
}

interface Enterprise {
  key?: string;
  name: string;
  growthRate: string;
  industry: string;
  status: string;
}

const RisingPage: React.FC = () => {
  const navigate = useNavigate();

  const [tableData, setTableData] = useState<Enterprise[]>([]);
  const [loading, setLoading] = useState(true);
  const [cardData, setCardData] = useState({
    total: 0,
    risingCount: 0,
    avgGrowth: '0.00%',
  });

  const columns = [
    {
      title: '企业名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Enterprise) => (
        <a
          onClick={() => navigate(`/enterprise/${record.name}`)}
          style={{ color: '#1890ff', cursor: 'pointer', fontWeight: 'bold' }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '增长率',
      dataIndex: 'growthRate',
      key: 'growthRate',
      render: (text: string) => <Tag color="green">{text}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: string) => (
        <Tag color={text === '快速增长' ? 'blue' : text === '稳定增长' ? 'gold' : 'red'}>
          {text}
        </Tag>
      ),
    },
  ];

  const tableContainerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const container = tableContainerRef.current;
    if (!container) return;
    let scrollInterval: NodeJS.Timeout;
    const startScrolling = () => {
      scrollInterval = setInterval(() => {
        container.scrollTop += 1;
        if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
          container.scrollTop = 0;
        }
      }, 50);
    };
    startScrolling();
    return () => {
      clearInterval(scrollInterval);
    };
  }, []);

  useEffect(() => {
    axios
      .get<RisingResponse>('http://localhost:5000/api/rising')
      .then((response) => {
        const data = response.data;
        const processedData = data.companies.map((item) => ({
          ...item,
          key: item.name,
        }));
        setTableData(processedData);
        setLoading(false);

        const totalGrowth = processedData.reduce((sum, cur) => {
          const rate = parseFloat(cur.growthRate.replace('%', '')) || 0;
          return sum + rate;
        }, 0);
        const avgGrowth = processedData.length > 0 ? (totalGrowth / processedData.length).toFixed(2) : '0.00';

        setCardData({
          total: processedData.length,
          risingCount: data.totalRisingCompanies,
          avgGrowth: `${avgGrowth}%`,
        });
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  const rankingData = [...tableData]
    .sort((a, b) => {
      const rateA = parseFloat(a.growthRate.replace('%', '')) || 0;
      const rateB = parseFloat(b.growthRate.replace('%', '')) || 0;
      return rateB - rateA;
    })
    .slice(0, 10);

  const rankingColumns = [
    {
      title: '排名',
      key: 'rank',
      render: (_: unknown, _record: Enterprise, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Enterprise) => (
        <a
          onClick={() => navigate(`/enterprise/${record.name}`)}
          style={{ color: '#1890ff', cursor: 'pointer', fontWeight: 'bold' }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '增长率',
      dataIndex: 'growthRate',
      key: 'growthRate',
      render: (text: string) => <Tag color="green">{text}</Tag>,
    },
  ];

  return (
    <div
      style={{
        padding: '20px',
        background: 'linear-gradient(to bottom, #f0f5ff, #ffffff)',
        minHeight: '100vh',
      }}
    >
      <Title
        level={2}
        style={{
          textAlign: 'center',
          marginBottom: '30px',
          color: '#333',
          fontWeight: 'bold',
          textShadow: '1px 1px 2px rgba(0, 0, 0, 0.2)',
        }}
      >
        上升企业详情
      </Title>

      <Row gutter={[16, 16]} style={{ marginBottom: '30px' }}>
        <Col span={8}>
          <Card
            title="总企业数"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #e6f7ff, #ffffff)',
            }}
          >
            <Statistic
              value={cardData.total}
              valueStyle={{ color: '#1890ff', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            title="潜在增长企业"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #fffbe6, #ffffff)',
            }}
          >
            <Statistic
              value={cardData.risingCount}
              suffix="家"
              valueStyle={{ color: '#faad14', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            title="平均增长率"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #f6ffed, #ffffff)',
            }}
          >
            <Statistic
              value={cardData.avgGrowth}
              valueStyle={{ color: '#52c41a', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: '30px' }}>
        <Col span={24}>
          <Card
            title="增长率排行榜（前 10 名）"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              background: '#ffffff',
            }}
          >
            <Table
              dataSource={rankingData}
              columns={rankingColumns}
              pagination={false}
              loading={loading}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card
            title="企业增长列表"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
              background: '#ffffff',
            }}
          >
            <div
              ref={tableContainerRef}
              style={{
                maxHeight: '240px',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              <Table
                dataSource={tableData}
                columns={columns}
                pagination={false}
                scroll={{ y: 240 }}
                loading={loading}
                style={{ marginTop: '10px' }}
              />
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default RisingPage;
